package helper;

import helper.util.MapKeyComparator;
import org.apache.commons.codec.digest.DigestUtils;
import play.Logger;
import sun.misc.BASE64Encoder;

import java.security.MessageDigest;
import java.util.Map;
import java.util.TreeMap;

public class PinduoduoHelper {

    public static final String CLIENT_ID = "3a073e59064c4362adba84144275142b";
    public static final String CLIENT_SECURE = "78aa1347391c414e0db319dddd5681705c2b26df";

    /**
     * 获取密钥
     * @param signMap
     * @return
     */
    public static String sgin(Map<String , Object> signMap){
        signMap = sortMapByKey(signMap);
        StringBuilder signString = new StringBuilder();
        signString.append(CLIENT_SECURE);
        for(String key : signMap.keySet()) {
            signString.append(key);
            signString.append(signMap.get(key));
            Logger.info("Key : %s | value : %s" , key , signMap.get(key));
        }
        signString.append(CLIENT_SECURE);
        Logger.info("signString : %s" , signString.toString());
        String md5 = null;
        try {
            md5 = DigestUtils.md5Hex(signString.toString()).toUpperCase();
            Logger.info("MD5:%s" , md5);
            return md5;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 使用 Map按key进行排序
     * @param map
     * @return
     */
    public static Map<String, Object> sortMapByKey(Map<String, Object> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }

        Map<String, Object> sortMap = new TreeMap<String, Object>(
                new MapKeyComparator());

        sortMap.putAll(map);

        return sortMap;
    }

}

